# -*- coding: utf-8 -*-..,
##############################################################################
#
#    @author: PhongND
#    Copyright (C) 2014 Crea8s (http://www.crea8s.com) All Rights Reserved.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################


# -*- coding: UTF-8 -*-
'''
    magento

    :copyright: (c) 2014-2015 by PhongND
    :license: AGPLv3, see LICENSE for more details
'''
import magento
from openerp.osv import fields, osv
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp


# for logging
from StringIO import StringIO
import logging
_logger = logging.getLogger(__name__)
import traceback

class Partner(osv.Model):
    """Partner
    """
    _inherit = 'res.partner'

    _columns = dict(
        crea8s_magento_id=fields.integer('Magento ID', readonly=True),
        crea8s_magento_instance=fields.many2one(
            'crea8s.magento.instance', 'Magento Instance', readonly=True,
        ),
        crea8s_magento_website=fields.many2one(
            'crea8s.magento.website', 'Store View', readonly=True,
        ),
    )
    
    _sql_constraints = [(
        'magento_id_instance_unique', 'unique(crea8s_magento_id, crea8s_magento_instance)',
        'A partner must be unique in an instance' # PhongND
    )]
    
    
    def crea8s_find_or_create_using_magento_data(
        self, cursor, user, data_importing, context
    ):
        """
        Find or Create partner using magento data

        :param cursor: Database cursor
        :param user: ID of current user
        :param data_importing: Order Data from magento
        :param context: Application context
        :returns: Browse record of partner order found/created
        """
        partner = self.crea8s_find_using_magento_data(
            cursor, user, data_importing, context
        )
        
        if not partner:
#             return False
            partner = self.crea8s_create_using_magento_data(
                cursor, user, data_importing, context
            )
        else:
            partner = self.crea8s_create_using_magento_data(
                cursor, user, data_importing, context, updateID = partner.id
            )
            

        return partner

    def crea8s_find_using_magento_data(
        self, cursor, user, data_importing, context
    ):
        """
        Create partner using magento data

        :param cursor: Database cursor
        :param user: ID of current user
        :param data_importing: Order Data from magento
        :param context: Application context
        :returns: Browse record of partner order found
        """
        # each partner has to be unique in an instance of magento
        found_ids = None
        found_ids = self.search(cursor, user, [
            ('crea8s_magento_id', '=', int(data_importing['customer_id'])),
            ('crea8s_magento_website', '=', context.get('magento_website')),
        ], context=context)

        return found_ids and self.browse(
            cursor, user, found_ids[0], context
        ) or None


    def crea8s_create_using_magento_data(self, cursor, user, data_importing, context, updateID=None):
        """
        Create a partner order from magento data
 
        :param cursor: Database cursor
        :param user: ID of current user
        :param data_importing: Order Data from magento
        :param context: Application context
        :returns: Browse record of partner order created
        """
#         currency_obj = self.pool.get('res.currency')
#         store_view_obj = self.pool.get('magento.store.store_view')
#         partner_obj = self.pool.get('res.partner')
        
        magento_partner_obj = self.pool.get(
            'crea8s.magento.partner'
        )
        partner_id = 1
        magento_partner = None
        magento_partner_id = 0
        
        # find or create 'crea8s.magento.product_partner'
#         magento_partner = self.search(cursor, user, [
#                 ('crea8s_magento_id', '=', int(data_importing['customer_id'])),
#                 ('crea8s_magento_website', '=', context['magento_website'])
#             ], context=context)
        
#         if len(magento_partner) > 0:
#             magento_partner_id = magento_partner[0]
#         else:
#             magento_partner = magento_partner_obj.create(cursor, user, { 
#                 'magento_id': int(data_importing['customer_id']),
#                 'instance': context['magento_instance']
#                 }, context=context)
#             magento_partner_id = magento_partner
        
        print 'partner.py: crea8s_create_using_magento_data'
        print '+ magento_partner_id: ' + str(magento_partner_id)
        
        # finding country
        ormCountry = self.pool.get(
            'res.country'
        )
        country_ids = []
        country_id = None
        if data_importing.get('address'):
            country_ids = ormCountry.search(cursor, user, [('code', '=', data_importing.get('address').get('country_id'))], context=context)
        
        if len(country_ids) > 0:
            country_id = country_ids[0]
        
        # data
        arrData = {
                'name': u' '.join([data_importing['firstname'], data_importing['lastname']]),
                'email': data_importing['email'],
                'crea8s_magento_id': data_importing.get('customer_id'),
                'crea8s_magento_website': context['magento_website'],
                'phone': data_importing.get('address') and data_importing.get('address').get('telephone') or None,
                'fax': data_importing.get('address') and data_importing.get('address').get('fax') or None,
                'zip': data_importing.get('address') and data_importing.get('address').get('postcode') or None,
                'street': data_importing.get('address') and data_importing.get('address').get('street') or None,
                'company': data_importing.get('address') and data_importing.get('address').get('company') or None,
                'country_id':  country_id,
#                 'crea8s_magento_ids': [], #??,,
#                 'crea8s_magento_ids':  #??,, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#                     [(123, 0, {  # ??????  ; ... 123, 0, })]

            } 
        
        if updateID:
            partner_id = self.write(cursor, user, [updateID], arrData, context=context)
            partner_id = updateID
        else:
            partner_id = self.create(cursor, user, arrData, context=context)
            
        print '+ partner_id: ' + str(partner_id)
#         # update partner at 'crea8s.magento.product_partner'
#         magento_partner = magento_partner_obj.browse(cursor, user, magento_partner_id, context=context)
#         magento_partner_obj.write(cursor, user, magento_partner.id, {
#               'partner': partner_id, 
#                }, context=context)
        
        
        return self.browse(cursor, user, partner_id, context=context)
    
    
    
    def crea8s_find_or_create_using_magento_id(
        self, cursor, user, magento_id, context
    ):
        """
        Finds or creates partner using magento ID

        :param cursor: Database cursor
        :param user: ID of current user
        :param magento_id: Partner ID sent by magento
        :param context: Application context.
        :return: Browse record of record created/found
        """
        ormInstance = self.pool.get('crea8s.magento.instance')

        broPartner = self.crea8s_find_using_magento_id(cursor, user, magento_id, context)
        if not broPartner:
            instance = ormInstance.browse(
                cursor, user, context['magento_instance'], context=context
            )
            
            with magento.Customer(
                instance.url, instance.api_user, instance.api_key
            ) as customer_api:
                customer_data = customer_api.info(magento_id)
 
            broPartner = self.crea8s_create_using_magento_data(
                cursor, user, customer_data, context
            )
            
        return broPartner
    
    
    def crea8s_find_using_magento_id(self, cursor, user, magento_id, context):
        """
        Finds partner with magento id

        :param cursor: Database cursor
        :param user: ID of current user
        :param magento_id: Partner ID sent by magento
        :param context: Application context.
        :return: Browse record of record found
        """
#         magento_partner_obj = self.pool.get('magento.website.partner')
# 
#         record_ids = magento_partner_obj.search(
#             cursor, user, [
#                 ('magento_id', '=', magento_id),
#                 ('website', '=', context['magento_website'])
#             ], context=context
#         )
        found_ids = None
        found_ids = self.search(cursor, user, [
            ('crea8s_magento_id', '=', int(magento_id)),
            ('crea8s_magento_website', '=', context['magento_website']),
        ], context=context)

        return found_ids and self.browse(# AAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaa
            cursor, user, found_ids[0], context
        ) or None
        
#         return self.browse( 
#             cursor, user, 3, context
#         )

    
    def crea8s_find_or_create_address_as_partner_using_magento_data(
        self, cursor, user, address_data, parent, context
    ):
        """
        Find or Create an address from magento with `address_data` as a
        partner in openerp with `parent` as the parent partner of this address
        partner (how FUCKED^^ up is that).

        :param cursor: Database cursor
        :param user: ID of current user
        :param address_data: Dictionary of address data from magento
        :param parent: Parent partner for this address partner.
        :param context: Application context.
        :return: Browse record of address created/found
        """
        try: 
            for address in parent.child_ids + [parent]:
                iCount = 0
                self.crea8s_match_address_with_magento_data(
                    cursor, user, address, address_data
                )
#                 self.crea8s_create_address_as_partner_using_magento_data(
#                         cursor, user, address_data, parent, context
#                     )



#                 if self.crea8s_match_address_with_magento_data(
#                     cursor, user, address, address_data
#                 ):
#                     break
#                 else:
#                     address = self.crea8s_create_address_as_partner_using_magento_data(
#                         cursor, user, address_data, parent, context
#                     )
#     
#             return address
            return None
        
        except: # catch all exception.....
            
            _logger.error('crea8s_find_or_create_address_as_partner_using_magento_data-error: FALSE')
            buff = StringIO()
            traceback.print_exc(file=buff)
            _logger.error(buff.getvalue())
        
    
    def crea8s_match_address_with_magento_data(
        self, cursor, user, address, address_data
    ):
        """Match the `address` in openerp with the `address_data` from magento
        If everything matches exactly, return True, else return False

        :param cursor: Database cursor
        :param user: ID of current user
        :param address: Browse record of address partner
        :param address_data: Dictionary of address data from magento
        :return: True if address matches else False
        """
        # Check if the name matches
        if address.name != u' '.join(
            [address_data['firstname'], address_data['lastname']]
        ):
            return False

        if not all([
#             (address.street or None) == address_data['street'],
            (address.phone or None) == address_data['telephone'],
            (address.email or None) == address_data['email'],
#             (address.fax or None) == address_data['fax'],
#             (address.zip or None) == address_data['postcode'],
#             (address.city or None) == address_data['city'],
#             (address.state_id and address.state_id.name or None) ==
#                 address_data['region'] 
#             (address.country_id and address.country_id.code or None) ==
#                 address_data['country_id'],
        ]):
            return False

        return True
        
    
    def crea8s_create_address_as_partner_using_magento_data(  #  AAA
        self, cursor, user, address_data, parent, context
    ):
        """Create a new partner with the `address_data` under the `parent`

        :param cursor: Database cursor
        :param user: ID of current user
        :param address_data: Dictionary of address data from magento
        :param parent: Parent partner for this address partner.
        :param context: Application Context
        :return: Browse record of address created
        """
        
        try:
            ormCountry = self.pool.get('res.country')
            ormState = self.pool.get('res.country.state')
            
            country_ids = []
            country_id = None
            country_ids = ormCountry.search(cursor, user, [('code', '=', address_data.get('country_id'))], context=context) #== ormCountry.search_using_magento_code
        
            if len(country_ids) > 0:
                country_id = country_ids[0]
            
        #         if address_data['region']:
        #             state_id = ormState.crea8s_find_or_create_using_magento_region(
        #                 cursor, user, country, address_data['region'], context
        #             ).id
        #         else:
        #             state_id = None
                
            address_id = self.create(cursor, user, {
                'name': u' '.join(
                    [address_data['firstname'], address_data['lastname']]
                ),
                'street': address_data['street'],
                'state_id': None, #state_id,
                'country_id': country_id,
                'city': address_data['city'],
                'zip': address_data['postcode'],
                'phone': address_data['telephone'],
                'fax': address_data['fax'],
                'parent_id': parent.id,
            }, context=context)
        
            return self.browse(cursor, user, address_id, context=context)
        
        except: # catch all exception.....
            
            _logger.error('crea8s_find_or_create_address_as_partner_using_magento_data-error: FALSE')
            buff = StringIO()
            traceback.print_exc(file=buff)
            _logger.error(buff.getvalue())
    
    
class MagentoWebsitePartner02(osv.Model):
    """Magento Website - Partner store

    This model keeps a record of a partner's association with a website and
    the ID of partner on that website
    """
    _name = 'crea8s.magento.partner'
    _description = 'Magento Website - Partner store'

    _columns = dict(
        magento_id=fields.integer(
            'Magento ID', select=True, #, required=True
        ),

        instance=fields.many2one(
            'crea8s.magento.instance', 'Magento Instance', readonly=True,
            select=True, required=True
        ),
                    
        partner=fields.many2one(
            'res.partner', 'Partner', readonly=True,
             select=True,
        )
    )

    _sql_constraints = [
        (
            'magento_id_instance_unique',
            'unique(magento_id, instance)',
            'Each crea8s.magento.partner in a instance must be unique!'
        ),
    ]


